<template>
  <el-dialog
    :visible="subjectAddStatus"
    :title="subjectData ? '修改学科' : '新增学科'"
    @close="btnCancel"
    width="400px"
  >
    <el-form
      ref="subjectForm"
      :model="subjectForm"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="学科名称" prop="subjectName">
        <el-input
          v-model="subjectForm.subjectName"
          style="width: 80%"
          placeholder="请输入目录名称"
      /></el-form-item>
      <el-form-item label="是否显示" prop="isFrontDisplay">
        <el-switch
          v-model="subjectForm.isFrontDisplay"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-button type="primary" size="small" @click="btnOK">确定</el-button>
      <el-button size="small" @click="btnCancel">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  props: {
    subjectAddStatus: {
      type: Boolean,
      default: false
    },
    subjectData: {
      type: Object
    }
  },
  data () {
    return {
      subjectForm: {
        subjectName: '',
        isFrontDisplay: 1
      },
      rules: {
        subjectName: [{ required: true, message: '学科名称不能为空', trigger: 'blur' }],
        isFrontDisplay: [{ required: true, trigger: 'change' }]
      }
    }
  },
  created () {
    if (this.subjectData) {
      this.subjectForm.subjectName = this.subjectData.subjectName
      this.subjectForm.isFrontDisplay = this.subjectData.isFrontDisplay
    }
  },
  methods: {
    btnOK () {
      this.$refs.subjectForm.validate()
        .then(() => {
          if (this.subjectData) {
            update({ id: this.subjectData.id, ...this.subjectForm })
          } else add(this.subjectForm)
        }).then(() => {
          this.$message.success(this.subjectData ? '修改学科成功' : '新增学科成功')
          this.$emit('refreshDataList')
          this.btnCancel()
        }).catch((err) => {
          console.log(err)
          this.$message.error(err)
        })
    },
    btnCancel () {
      this.$emit('update:subjectAddStatus', false)
      this.$emit('update:subjectData', null)
    }
  }
}
</script>

<style scoped lang='scss'></style>
